<template>
  <div>
    <el-empty v-show="!this.shopInfo.id" description="您还没有店铺">
      <el-button type="text" @click="createShop">创建店铺</el-button>
    </el-empty>
    <div v-show="this.shopInfo.id" class="app-container">
      <div class="description" style="margin-bottom: 30px">
        <el-descriptions
          class="margin-top"
          title="店铺基本信息"
          :column="3"
          border
        >
          <template slot="extra">
            <el-button type="primary" size="small" @click="shopEdit"
              >店铺信息修改</el-button
            >
            <el-button type="primary" size="small" @click="createQRCode"
              >收款码</el-button
            >

            <el-button
              type="primary"
              size="small"
              @click="downloadCode"
              v-show="this.shopInfo.filePath"
              >店铺码</el-button
            >
          </template>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              店铺名称
            </template>
            {{ shopInfo.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone"></i>
              联系电话
            </template>
            {{ shopInfo.tel }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-shopping-cart-2"></i>
              营业时间
            </template>
            {{ shopInfo.startTime }} —— {{ shopInfo.endTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-tickets"></i>
              店铺状态
            </template>
            <el-tag size="small">{{
              shopInfo.status === 1 ? "营业" : "未营业"
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-location-outline"></i>
              联系地址
            </template>
            {{ shopInfo.address }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              店铺描述
            </template>
            {{ shopInfo.description }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 添加或修改店铺对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="openshop"
          width="500px"
          append-to-body
        >
          <el-form
            ref="form2"
            :model="formshop"
            :rules="rules2"
            label-width="80px"
          >
            <el-form-item label="店铺名字" prop="name">
              <el-input v-model="formshop.name" placeholder="请输入名字" />
            </el-form-item>
            <el-form-item label="店铺描述" prop="description">
              <el-input
                v-model="formshop.description"
                placeholder="请输入店铺描述"
              />
            </el-form-item>
            <!-- <el-form-item label="所属人Id" prop="personId">
          <el-input v-model="formshop.personId" placeholder="请输入所属人Id" />
        </el-form-item> -->
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="formshop.tel" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="营业开始时间" prop="startTime">
              <el-time-select
                placeholder="起始时间"
                v-model="formshop.startTime"
                :picker-options="{
                  start: '06:30',
                  step: '00:15',
                  end: '22:30',
                }"
              >
              </el-time-select>
            </el-form-item>
            <el-form-item label="营业结束时间" prop="endTime">
              <el-time-select
                placeholder="结束时间"
                v-model="formshop.endTime"
                :picker-options="{
                  start: '06:30',
                  step: '00:15',
                  end: '22:30',
                  minTime: formshop.startTime,
                }"
              >
              </el-time-select>
            </el-form-item>
            <el-form-item label="营业状态" prop="status">
              <el-radio-group v-model="formshop.status" size="small">
                <el-radio-button
                  v-for="item in shopStatus"
                  :key="item.id"
                  :label="item.id"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="formshop.address" placeholder="请输入地址" />
            </el-form-item>
            <!-- <el-form-item label="排序字段" prop="sort">
          <el-input v-model="formshop.sort" placeholder="请输入排序字段" />
        </el-form-item> -->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFormShop">确 定</el-button>
            <el-button @click="shopCancel">取 消</el-button>
          </div>
        </el-dialog>
      </div>

      <!-- 二维码 -->
      <el-dialog
        title="店铺二维码"
        :visible.sync="dialogVisibleCode"
        width="30%"
        :close-on-click-modal="false"
      >
        <div class="demo-image__preview">
          <el-image style="width: 100%" :src="url + this.shopInfo.filePath">
          </el-image>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="useCode">下载店铺码</el-button>
          <el-button @click="createShopCode">生成店铺码</el-button>
          <el-button type="primary" @click="dialogVisibleCode = false"
            >关闭</el-button
          >
        </span>
      </el-dialog>

      <el-dialog title="收款码" :visible.sync="dialogVisibleCode2" width="30%">
        <div class="demo-image__preview">
          <el-image
            style="width: 100%"
            :src="url + this.shopInfo.filePathMoney"
          >
          </el-image>
        </div>
        <el-upload
          class="upload-demo"
          :action="uploadUrl2"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-upload="beforeUplad"
          :on-success="filesuccess2"
          :headers="headers"
          :data="{ shopId: this.shopInfo.id }"
        >
          <!-- <img
            v-show="this.shopInfo.filePathMoney"
            :src="url + this.shopInfo.filePathMoney"
            class="avatar"
            style="width: 300px; height: 300px;"
          /> -->

          <el-button size="small" type="primary">点击上传</el-button>

          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="useCode">上传收款码</el-button> -->
          <el-button type="primary" @click="dialogVisibleCode2 = false"
            >关闭</el-button
          >
        </span>
      </el-dialog>

      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="商品名字" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名字"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="queryParams.description"
            placeholder="请输入商品描述"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->

        <el-form-item label="是否开启团购" prop="price">
          <el-select
            v-model="queryParams.ptStatus"
            placeholder="请选择"
            clearable
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['product:item:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['product:item:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['product:item:remove']"
            >删除</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        border
        :data="itemList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="id" align="center" key="id" prop="id" /> -->
        <el-table-column label="名字" align="center" key="name" prop="name" />
        <el-table-column
          label="图片(点击上传)"
          align="center"
          key="remark"
          prop="picture"
        >
          <!-- <img :src="form.filePath"  /> -->

          <template slot-scope="scope">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="beforeUplad"
              :on-success="filesuccess"
              :headers="headers"
              :data="{ projectId: scope.row.id }"
            >
              <img
                v-if="scope.row.filePath"
                :src="url + scope.row.filePath"
                class="avatar"
                style="width: 300px; height: 150px"
              />
              <i
                v-else
                class="el-icon-upload avatar-uploader-icon"
                style="color: #409eff; font-size: 30px"
              ></i>
              <!-- <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div> -->
            </el-upload>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="商铺ID"
          align="center"
          key="shopId"
          prop="shopId"
        /> -->
        <!-- <el-table-column
        header-align="center"
        prop="filePath"
        align="center"
        label="首页展示图片"
      >
        <template slot-scope="scope">
          <img
            v-show="scope.row.filePath"
            :src="BaseUrl + scope.row.filePath"
            min-width="300"
            height="150"
          />
        </template>
      </el-table-column> -->

        <el-table-column
          label="商品描述"
          align="center"
          key="description"
          prop="description"
        />
        <el-table-column
          label="需要的时间(分钟)"
          align="center"
          key="needTime"
          prop="needTime"
        />
        <el-table-column label="价格" align="center" key="price" prop="price">
          <template slot-scope="scope"> ￥：{{ scope.row.price }} </template>
        </el-table-column>

        <el-table-column
          label="人工费"
          align="center"
          key="manHourCost"
          prop="manHourCost"
        >
          <template slot-scope="scope">
            ￥：{{ scope.row.manHourCost }}/小时
          </template>
        </el-table-column>
        <el-table-column
          label="所需产品"
          align="center"
          key="goods"
          prop="goods"
        >
          <template slot-scope="scope">
            <el-tag v-for="item in scope.row.goods" :key="item.id">{{
              item.name + " X" + item.sum
            }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="成本" align="center" key="cost" prop="cost" /> -->

        <!-- <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"> -->
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
        <!-- <el-table-column label="排序字段" align="center" key="sort" prop="sort" /> -->
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['product:item:edit']"
              >详情</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-notebook-1"
              @click="goodsInfo(scope.row)"
              v-hasPermi="['product:item:edit']"
              >关联商品</el-button
            >
            <el-button
              size="mini"
              type="text"
              style="color: red"
              icon="el-icon-setting"
              @click="pintuan(scope.row)"
              v-hasPermi="['product:item:edit']"
              >拼团设置</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['product:item:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.rowsPerPage"
        @pagination="getList"
      />

      <!-- 添加商品dialog -->
      <el-dialog
        :title="!goodInfo.pgId ? '新增' : '修改'"
        :append-to-body="true"
        :visible.sync="dialogFormVisible"
        :show-close="false"
        width="500px"
      >
        <el-form :model="goodInfo" ref="goodInfo" :rules="rules3">
          <el-form-item
            v-show="!goodInfo.pgId"
            label="商品名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <!-- <el-input v-model="goodInfo.name" autocomplete="off"></el-input> -->
            <el-select
              v-model="goodInfo.name"
              placeholder="请选择产品"
              @change="changeGood"
            >
              <el-option
                v-for="item in dic"
                :label="item.label"
                :value="item.label"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品数量"
            :label-width="formLabelWidth"
            prop="sum"
          >
            <el-input
              class="inputSum"
              v-model="goodInfo.sum"
              style="width: 220px"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeNotSave">取 消</el-button>
          <el-button type="primary" @click="closeGoods">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 商品关联 -->
      <el-dialog
        :title="title2"
        :visible.sync="dialogVisible2"
        width="30%"
        @close="ItemAndGoodClosed"
      >
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin-left: 10px"
          @click="addGoods(form.id)"
        >
          添加关联商品
        </el-button>
        <el-table
          style="width: 100%; margin-top: 10px"
          :data="productList"
          border
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="name" label="属性名" width="width">
          </el-table-column>
          <el-table-column prop="sum" label="数量" width="width">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="updateGood(scope.row, scope.$index)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="goodDelete(scope.row, scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <span slot="footer" class="dialog-footer">
          <el-button @click="closeItemAndGood">关闭</el-button>
          <!-- <el-button type="primary" @click="dialogVisible = false"
            >确 定</el-button
          > -->
        </span>
      </el-dialog>

      <!-- 添加或修改商家品项对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        @close="productClosed"
        width="800px"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="名字" prop="name">
                <el-input v-model="form.name" placeholder="请输入名字" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品描述" prop="description">
                <el-input
                  v-model="form.description"
                  placeholder="请输入商品描述"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="时间(分钟)" prop="needTime">
                <el-input
                  v-model="form.needTime"
                  placeholder="请输入需要的时间(分钟)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="价格" prop="price">
                <el-input v-model="form.price" placeholder="请输入价格" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="人工费" prop="manHourCost">
                <el-input
                  v-model="form.manHourCost"
                  placeholder="请输入人工费"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 拼团 -->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="是否开启拼团" prop="ptStatus">
            <el-radio-group v-model="form.ptStatus" size="medium">
              <el-radio-button label="开启"></el-radio-button>
              <el-radio-button label="关闭"></el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="拼团价格" prop="ptPrice">
            <el-input v-model="form.ptPrice" placeholder="请输入拼团价格" />
          </el-form-item>
          <el-form-item label="成团人数" prop="ptPersonTotal">
            <el-input
              v-model="form.ptPersonTotal"
              placeholder="请输入成团人数"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel2">取 消</el-button>
          <el-button type="primary" @click="submitForm2">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  listItem,
  getItem,
  delItem,
  addItem,
  updateItem,
  getShop,
  getDic,
  updateShop,
  getItemById,
  delItemAndgood,
  updateOrAdd,
  createCode,
  getFileById,
} from "@/api/product/item";
import { getToken } from "@/utils/auth";
import url from "@/api/product/url";

export default {
  name: "Item",
  data() {
    return {
      //二维码"http://ix62hd.natappfree.cc/api/work/file/D://upload//qrCode//1.png"
      url: url.httpUrl,
      isupload: false,
      fileList: [],
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploadUrl: url.httpUrl + "/work/shop/uploadProjectPic", // 上传的图片服务器地址
      uploadUrl2: url.httpUrl + "/work/shop/uploadMoneyPic", // 上传的图片服务器地址
      // 项目id
      projectId: "",
      shopStatus: [
        {
          id: 0,
          label: "未营业",
        },
        {
          id: 1,
          label: "营业",
        },
      ],
      dialogFormVisible: false,
      formLabelWidth: "100px",
      num: 1,
      productList: [],
      oldSum: 0,
      nowIndex: 0,
      dic: [],
      oldDic: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商家品项表格数据
      itemList: [],
      // 登录人店铺信息
      shopInfo: {},
      goodInfo: {},
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisibleCode: false,
      dialogVisibleCode2: false,
      // 弹出层标题
      title: "",
      title2: "",
      // 是否显示弹出层
      open: false,
      openshop: false,
      // 查询参数
      queryParams: {
        page: 1,
        rowsPerPage: 10,
        name: null,
        shopId: null,
        // description: null,
        // needTime: null,
        // price: null,
        // isRealtion: null,
        // cost: null,
        // createBy: null,
        // createTime: null,
        // sort: null,
        ptStatus: null,
      },
      options: [
        {
          value: "开启",
          label: "开启",
        },
        {
          value: "关闭",
          label: "关闭",
        },
      ],
      // 表单参数
      form: {},
      formshop: {},
      // 表单校验
      rules: {},
      rules2: {
        name: [
          { required: true, message: "店铺名称不能为空", trigger: "blur" },
        ],
        // password: [
        //   { required: true, message: "用户密码不能为空", trigger: "blur" },
        //   { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        // ],
        // startTime:[{
        //   type:"date",required:true,message:"请选择日期",trigger:"change"
        // }],
        //  endTime:[{
        //   type:"date",required:true,message:"请选择日期",trigger:"change"
        // }],
        // email: [
        //   {
        //     type: "email",
        //     message: "请输入正确的邮箱地址",
        //     trigger: ["blur", "change"]
        //   }
        // ],
        address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
        tel: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        //  introduce: [
        //   { required: true, message: "自我介绍不能为空", trigger: "blur" }
        // ],
      },
      rules3: {
        name: [{ required: true, message: "产品不能为空", trigger: "blur" }],
        sum: [
          { required: true, message: "数量不能为空", trigger: "blur" },
          {
            pattern: /^[0-9]\d*$/,
            message: "必须为整数",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getShopInfo();
  },
  methods: {
    beforeUplad(file) {
      // if (this.form.fileId) {
      //   delFilebyId(this.form.fileId).then((res) => {
      //     if (res && res.code === 200) {
      //       // this.$message({
      //       //   message: "文件删除成功",
      //       //   type: "success",
      //       //   duration: 1500,
      //       // });
      //     } else {
      //       this.$message.error(data.msg);
      //     }
      //   });
      // }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 上传成功后的回调函数
    filesuccess(res, file, fileList) {
      if (res.code == 200) {
        this.getList();
        // this.isupload = true;
        // this.form.fileId = res.data;
        // // this.sizeForm.fileList.push(file);
        // getFilebyId(res.data).then((res) => {
        //   if (res.code === 200) {
        //     this.form.filePath =
        //       process.env.VUE_APP_BASE_API + res.data.filePath;
        //     this.$message({
        //       message: "文件上传成功",
        //       type: "success",
        //       duration: 1500,
        //     });
        //   }
        // });
        console.log("数据" + res.data);
      }
    },

    filesuccess2(res, file, fileList) {
      if (res.code == 200) {
        // getFileById(res.data).then((res) => {
        //   console.log("res", res);
        //   this.shopInfo.filePathMoney = res.data.filePath;
        // });
        // // this.isupload = true;
        // // this.form.fileId = res.data;
        // // // this.sizeForm.fileList.push(file);
        // // getFilebyId(res.data).then((res) => {
        // //   if (res.code === 200) {
        // //     this.form.filePath =
        // //       process.env.VUE_APP_BASE_API + res.data.filePath;
        // //     this.$message({
        // //       message: "文件上传成功",
        // //       type: "success",
        // //       duration: 1500,
        // //     });
        // //   }
        // // });
        // console.log("数据" + res.data);
        this.getShopInfo();
      }
    },
    useCode() {
      this.downCode(this.url + this.shopInfo.filePath, "pic");
    },

    downCode(imgsrc, name) {
      var image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;

        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png");
        var a = document.createElement("a");
        // 创建一个单击事件
        var event = new MouseEvent("click");
        a.download = name;
        a.href = url;

        // 触发a的单击事件
        a.dispatchEvent(event);
      };
      image.src = imgsrc;
    },

    //下载店铺码
    downloadCode() {
      this.dialogVisibleCode = true;
    },
    //生成店铺码
    createShopCode() {
      createCode().then((res) => {
        if (res.code === 200) {
          this.$modal.msgSuccess("创建成功");
          this.getShopInfo();
        }
      });
    },

    createQRCode() {
      this.dialogVisibleCode2 = true;
    },
    //设置拼团
    pintuan(row) {
      this.reset();
      const id = row.id || this.ids;

      getItemById(id).then((res) => {
        this.form = res.data;
        this.dialogVisible = true;
      });
    },
    // 创建点铺
    createShop() {
      this.reset();
      this.openshop = true;
    },
    // 修改店铺信息
    shopEdit() {
      this.openshop = true;
      getShop().then((response) => {
        this.formshop = response.data;
      });
    },
    getDicItem() {
      getDic(this.shopInfo.id).then((res) => {
        this.dic = res.data;
        this.oldDic = res.data;
      });
    },

    //增加商品
    addGoods(id) {
      let ids = this.productList.map((e) => {
        return e.id;
      });

      if (ids) {
        this.dic = this.dic.filter(
          (e) => ids.findIndex((i) => e.value === i) == -1
        );
      }

      this.goodInfo = {};
      this.dialogFormVisible = true;
    },

    //修改商品
    updateGood(row, index) {
      this.goodInfo = JSON.parse(JSON.stringify(row));
      console.log("goodInfo", this.goodInfo);
      this.oldSum = row.sum;
      this.dialogFormVisible = true;
      this.nowIndex = index;
      console.log("当前索引", this.nowIndex);
      // this.$set(this.goodInfo, "IndexId", index)
    },

    //关闭产品关联
    closeItemAndGood() {
      this.dialogVisible2 = false;
      this.getList();
    },

    closeNotSave() {
      this.dic = this.oldDic;
      this.dialogFormVisible = false;
      if (this.goodInfo.pgId) {
        let input = document.querySelector(".inputSum .el-input__inner");
        input.value = this.oldSum;
        this.productList = this.productList.map((e) => {
          console.log(this.goodInfo.pgId);
          if (e.pgId == this.goodInfo.pgId) {
            e.sum = this.oldSum;
            console.log(this.oldSum);
          }
          return e;
        });
      }
      this.goodInfo = {};
    },

    changeGood(e) {
      console.log("event" + e);
      let good = this.dic.filter((item) => item.label == e);
      this.$set(this.goodInfo, "id", good[0].value);
    },

    closeGoods() {
      this.$refs["goodInfo"].validate((valid) => {
        if (valid) {
          if (!this.goodInfo.pgId) {
            let form = {
              goodId: this.goodInfo.id,
              projectId: this.projectId,
              shopId: this.goodInfo.id,
              sum: this.goodInfo.sum,
            };

            updateOrAdd(form).then((res) => {
              if (res.code === 200) {
                this.$modal.msgSuccess("新增成功");
                getItemById(this.projectId).then((res) => {
                  this.productList = JSON.parse(JSON.stringify(res.data.goods));
                  this.dialogFormVisible = false;
                });
              }
            });
          } else {
            let form = {
              goodId: this.goodInfo.id,
              id: this.goodInfo.pgId,
              projectId: this.projectId,
              shopId: this.goodInfo.id,
              sum: this.goodInfo.sum,
            };
            // this.$set(this.goodInfo, "IndexId", index)
            // this.$set(this.productList, this.nowIndex, this.goodInfo);
            updateOrAdd(form).then((res) => {
              if (res.code === 200) {
                this.$modal.msgSuccess("修改成功");
                getItemById(this.projectId).then((res) => {
                  this.productList = JSON.parse(JSON.stringify(res.data.goods));
                  this.dialogFormVisible = false;
                });
              }
            });
          }
        }
      });
    },
    // 获取登录人店铺
    getShopInfo() {
      getShop().then((response) => {
        if (response.data) {
          this.shopInfo = response.data;
          this.getList();
          this.getDicItem();
        }
      });
    },
    /** 查询商家品项列表 */
    getList() {
      this.loading = true;
      this.queryParams.shopId = this.shopInfo.id;
      listItem(this.queryParams).then((response) => {
        this.itemList = response.data.list;
        this.total = response.data.totalCount;
        this.loading = false;
      });
    },

    // 品相取消按钮
    cancel() {
      this.getList();
      this.reset();
      this.open = false;
    },
    shopCancel() {
      this.openshop = false;
      this.resetShop();
    },
    /**品相dialog关闭*/
    productClosed() {
      this.getList();
      this.productList = [];
      this.reset();
    },

    // 关联商品关闭
    ItemAndGoodClosed() {
      console.log("关闭");
      this.productList = [];
      this.projectId = "";
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        shopId: null,
        description: null,
        needTime: null,
        price: null,
        isRealtion: null,
        cost: null,
        remark: null,
        createBy: null,
        createTime: null,
        sort: null,
        goods: [],
      };
      this.resetForm("form");
    },
    resetShop() {
      this.formshop = {
        id: null,
        name: null,
        description: null,
        personId: null,
        tel: null,
        startTime: null,
        endTime: null,
        address: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        sort: null,
      };
      this.resetForm("form2");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams.name = "";
      this.queryParams.ptStatus = "";
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.shopId = this.shopInfo.id;
      this.title = "添加商家品项";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      console.log("id" + id);
      getItemById(id).then((res) => {
        this.form = res.data;
        this.open = true;
        this.title = "修改商家品相";
        // this.productList = JSON.parse(JSON.stringify(res.data.goods));
      });
    },

    // 关联商品
    goodsInfo(row) {
      this.productList = [];
      const id = row.id || this.ids;
      this.projectId = row.id;
      getItemById(id).then((res) => {
        // this.form = res.data;
        this.dialogVisible2 = true;
        this.title2 = "关联商品";
        this.productList = JSON.parse(JSON.stringify(res.data.goods));
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateItem(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            updateItem(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /**拼团确定 */
    submitForm2() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateItem(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false;
              this.getList();
            });
          } else {
            updateItem(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.getList();
            });
          }
        }
      });
    },

    // 拼团取消
    cancel2() {
      this.getList();
      this.reset();
      this.dialogVisible = false;
    },
    /** 店铺信息修改或者新增 */
    submitFormShop() {
      this.$refs["form2"].validate((valid) => {
        if (valid) {
          if (this.formshop.id != null) {
            updateShop(this.formshop).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.openshop = false;
              this.getShopInfo();
            });
          } else {
            updateShop(this.formshop).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.openshop = false;
              this.getShopInfo();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商家品项编号为"' + ids + '"的数据项？')
        .then(function () {
          return delItem(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/item/export",
        {
          ...this.queryParams,
        },
        `item_${new Date().getTime()}.xlsx`
      );
    },
    //商品删除
    goodDelete(row, index) {
      console.log("rowID", row.pgId);
      this.$modal
        .confirm('是否确认删除商品号为"' + row.pgId + '"的数据项？')
        .then(function () {
          return delItemAndgood(row.pgId);
        })
        .then(() => {
          getItemById(this.projectId).then((res) => {
            this.productList = JSON.parse(JSON.stringify(res.data.goods));
          });
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});

      // this.productList.splice(index, 1);
    },
  },
};
</script>
